<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Message, Modal } from '@arco-design/web-vue'
import { useMerchantStore } from '@/stores/merchant'
import { updateMerchant } from '@/api/merchant'
import type { Merchant } from '@/api/merchant'

const router = useRouter()
const merchantStore = useMerchantStore()
const loading = ref(false)
const editMode = ref(false)

// 商家信息表单
const merchantForm = reactive<Partial<Merchant>>({
  name: '',
  address: '',
  phone: '',
  description: '',
  image: '',
  businessHours: '',
  deliveryFee: 0,
  minOrderAmount: 0,
  categoryId: 0,
  status: 1  // 添加默认状态值
})

// 初始化数据
onMounted(async () => {
  loading.value = true
  try {
    // 如果store中没有商家信息，则获取
    if (!merchantStore.currentMerchant) {
      await merchantStore.fetchCurrentMerchant()
    }
    
    // 如果获取失败或仍然没有商家信息，跳转到登录页
    if (!merchantStore.currentMerchant) {
      throw new Error('获取商家信息失败')
    }
    
    // 初始化表单数据
    Object.assign(merchantForm, {
      name: merchantStore.currentMerchant.name,
      address: merchantStore.currentMerchant.address,
      phone: merchantStore.currentMerchant.phone,
      description: merchantStore.currentMerchant.description,
      image: merchantStore.currentMerchant.image,
      businessHours: merchantStore.currentMerchant.businessHours,
      deliveryFee: merchantStore.currentMerchant.deliveryFee,
      minOrderAmount: merchantStore.currentMerchant.minOrderAmount,
      categoryId: merchantStore.currentMerchant.categoryId,
      status: merchantStore.currentMerchant.status || 1  // 确保status有值
    })
  } catch (error) {
    console.error('获取商家信息失败:', error)
    Message.error('获取商家信息失败，请稍后再试')
    
    // 如果获取商家信息失败，可能是token无效，跳转到登录页
    router.push('/merchant/login')
  } finally {
    loading.value = false
  }
})

// 切换编辑模式
const toggleEditMode = () => {
  if (editMode.value) {
    // 取消编辑，恢复原始数据
    if (merchantStore.currentMerchant) {
      Object.assign(merchantForm, {
        name: merchantStore.currentMerchant.name,
        address: merchantStore.currentMerchant.address,
        phone: merchantStore.currentMerchant.phone,
        description: merchantStore.currentMerchant.description,
        image: merchantStore.currentMerchant.image,
        businessHours: merchantStore.currentMerchant.businessHours,
        deliveryFee: merchantStore.currentMerchant.deliveryFee,
        minOrderAmount: merchantStore.currentMerchant.minOrderAmount,
        categoryId: merchantStore.currentMerchant.categoryId,
        status: merchantStore.currentMerchant.status || 1  // 确保status有值
      })
    }
  }
  
  editMode.value = !editMode.value
}

// 保存商家信息
const saveMerchantInfo = async () => {
  if (!merchantStore.currentMerchant) return
  
  // 确保status字段有值
  if (merchantForm.status === undefined || merchantForm.status === null) {
    merchantForm.status = 1
  }
  
  loading.value = true
  try {
    console.log('提交的商家信息:', merchantForm)
    const response = await updateMerchant(merchantStore.currentMerchant.id, merchantForm)
    
    if (response.code === 200) {
      // 更新store中的商家数据
      await merchantStore.fetchCurrentMerchant()
      
      Message.success('保存成功')
      editMode.value = false
    } else {
      throw new Error(response.message || '保存失败')
    }
  } catch (error: any) {
    console.error('保存商家信息失败:', error)
    Message.error('保存商家信息失败: ' + (error.message || '请稍后再试'))
  } finally {
    loading.value = false
  }
}

// 退出登录
const handleLogout = () => {
  Modal.confirm({
    title: '确认退出登录？',
    content: '退出后需要重新登录',
    onOk: () => {
      merchantStore.logout()
      Message.success('退出登录成功')
      router.push('/')
    }
  })
}

// 跳转到菜品管理
const goToDishManagement = () => {
  router.push('/merchant/dishes')
}

// 跳转到订单管理
const goToOrderManagement = () => {
  router.push('/merchant/orders')
}

// 返回首页
const goToHome = () => {
  router.push('/')
}
</script>

<template>
  <div class="merchant-dashboard-container">
    <a-spin :loading="loading" tip="加载中...">
      <!-- 标题栏 -->
      <div class="dashboard-header">
        <a-button shape="circle" @click="goToHome">
          <template #icon><icon-left /></template>
        </a-button>
        <h2>商家管理中心</h2>
        <div></div>
      </div>

      <div v-if="merchantStore.currentMerchant" class="dashboard-content">
        <!-- 左侧：商家信息 -->
        <div class="dashboard-left-column">
          <!-- 商家信息卡片 -->
          <div class="merchant-info">
            <div class="merchant-avatar">
              <a-avatar :size="100" :image-url="merchantStore.currentMerchant.image">
                <template #icon><icon-shop /></template>
              </a-avatar>
            </div>
            <div class="merchant-name">{{ merchantStore.currentMerchant.name }}</div>
            <div class="merchant-id">ID: {{ merchantStore.currentMerchant.id }}</div>
          </div>

          <!-- 功能菜单 -->
          <div class="merchant-menu">
            <a-list>
              <a-list-item @click="goToDishManagement">
                <template #extra><icon-right /></template>
                <a-list-item-meta>
                  <template #icon><icon-apps /></template>
                  <template #title>菜品管理</template>
                  <template #description>管理您的菜品和分类</template>
                </a-list-item-meta>
              </a-list-item>
              
              <a-list-item @click="goToOrderManagement">
                <template #extra><icon-right /></template>
                <a-list-item-meta>
                  <template #icon><icon-calendar /></template>
                  <template #title>订单管理</template>
                  <template #description>查看和处理订单</template>
                </a-list-item-meta>
              </a-list-item>
              
              <a-list-item @click="handleLogout">
                <template #extra><icon-right /></template>
                <a-list-item-meta>
                  <template #icon><icon-export /></template>
                  <template #title>退出登录</template>
                  <template #description>退出当前账号</template>
                </a-list-item-meta>
              </a-list-item>
            </a-list>
          </div>
        </div>

        <!-- 右侧：商家详细信息 -->
        <div class="dashboard-right-column">
          <!-- 商家详细信息 -->
          <div class="merchant-detail">
            <div class="detail-header">
              <h3>商家信息</h3>
              <a-button
                type="outline"
                :status="editMode ? 'danger' : 'normal'"
                @click="toggleEditMode"
              >
                {{ editMode ? '取消' : '编辑' }}
              </a-button>
            </div>

            <a-form
              :model="merchantForm"
              layout="vertical"
            >
              <a-form-item field="name" label="商家名称">
                <a-input
                  v-model="merchantForm.name"
                  placeholder="请输入商家名称"
                  :readonly="!editMode"
                />
              </a-form-item>
              
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item field="phone" label="联系电话">
                    <a-input
                      v-model="merchantForm.phone"
                      placeholder="请输入联系电话"
                      :readonly="!editMode"
                    />
                  </a-form-item>
                </a-col>
                
                <a-col :span="12">
                  <a-form-item field="businessHours" label="营业时间">
                    <a-input
                      v-model="merchantForm.businessHours"
                      placeholder="如：09:00-22:00"
                      :readonly="!editMode"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              
              <a-form-item field="address" label="商家地址">
                <a-input
                  v-model="merchantForm.address"
                  placeholder="请输入商家地址"
                  :readonly="!editMode"
                />
              </a-form-item>
              
              <a-form-item field="description" label="商家描述">
                <a-textarea
                  v-model="merchantForm.description"
                  placeholder="请输入商家描述"
                  :readonly="!editMode"
                />
              </a-form-item>
              
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item field="deliveryFee" label="配送费（元）">
                    <a-input-number
                      v-model="merchantForm.deliveryFee"
                      placeholder="配送费"
                      :min="0"
                      :step="1"
                      :disabled="!editMode"
                      style="width: 100%"
                    />
                  </a-form-item>
                </a-col>
                
                <a-col :span="12">
                  <a-form-item field="minOrderAmount" label="起送金额（元）">
                    <a-input-number
                      v-model="merchantForm.minOrderAmount"
                      placeholder="起送金额"
                      :min="0"
                      :step="5"
                      :disabled="!editMode"
                      style="width: 100%"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              
              <a-form-item field="image" label="商家图片">
                <a-input
                  v-model="merchantForm.image"
                  placeholder="请输入商家图片URL"
                  :readonly="!editMode"
                />
              </a-form-item>
              
              <a-button
                v-if="editMode"
                type="primary"
                long
                @click="saveMerchantInfo"
              >
                保存
              </a-button>
            </a-form>
          </div>
        </div>
      </div>
    </a-spin>
  </div>
</template>

<style scoped>
.merchant-dashboard-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.dashboard-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
}

.dashboard-header h2 {
  margin: 0;
  font-size: 24px;
  color: var(--color-text-1);
}

.dashboard-content {
  display: flex;
  gap: 24px;
}

/* 左侧列 */
.dashboard-left-column {
  display: flex;
  flex-direction: column;
  gap: 24px;
  width: 300px;
  flex-shrink: 0;
}

/* 右侧列 */
.dashboard-right-column {
  flex: 1;
}

.merchant-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px;
  background-color: var(--color-bg-2);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.merchant-avatar {
  margin-bottom: 20px;
}

.merchant-name {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 10px;
  color: var(--color-text-1);
  text-align: center;
}

.merchant-id {
  font-size: 14px;
  color: var(--color-text-3);
}

.merchant-detail {
  padding: 24px;
  background-color: var(--color-bg-2);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  height: 100%;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.detail-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--color-text-1);
}

.merchant-menu {
  background-color: var(--color-bg-2);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .merchant-dashboard-container {
    padding: 16px;
  }
  
  .dashboard-content {
    flex-direction: column;
  }
  
  .dashboard-left-column {
    width: 100%;
  }
  
  .merchant-info,
  .merchant-detail,
  .merchant-menu {
    padding: 16px;
  }
}

/* 表单样式优化 */
:deep(.arco-form-item) {
  margin-bottom: 20px;
}

:deep(.arco-input),
:deep(.arco-input-password),
:deep(.arco-textarea),
:deep(.arco-select) {
  border-radius: 6px;
}

/* 按钮样式优化 */
:deep(.arco-btn) {
  border-radius: 6px;
  height: 40px;
  font-weight: 500;
}
</style> 